/**
 * 主文件（main.js）
 * 执行策略：流式处理 enhancedSelectGroups（避免内存爆炸）
 * 每期输出预测情况到 JSONL 文件
 */

const path = require("path");
const fs = require("fs");
const _ = require("lodash");
const esm = require("esm");
const requireModule = esm(module);

const { readAllValues } = require("../awakened-potential/helpers/readAllValues.js");
const { calcAccuracySummary } = require("./calcAccuracySummary.js");
const getNumberGroupMap = require("../awakened-potential/modules/cjs/getNumberGroupMap.js");
const checkAccuracy = require("./checkAccuracy.js");
const enhancedSelectGroups = require("./enhancedSelectGroups.js");

const { flatGroupMap } = requireModule("../awakened-potential/helpers/readGroup.js");

// 构建所有号码
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  i + 1 < 10 ? `0${i + 1}` : `${i + 1}`
);
const numberGroupMap = getNumberGroupMap(allNumbers, flatGroupMap);

const historyData = readAllValues("m");
const historyNumbers = historyData.map((item) => item.number);
const slidingPairs = _.range(0, historyNumbers.length - 1).map((i) =>
  historyNumbers.slice(i, i + 2)
);

const groupAccuracyMap = _.mapValues(flatGroupMap, (v, groupName) => {
  return slidingPairs.map(([prev, curr]) => {
    const subIndex = numberGroupMap[prev][groupName];
    const subGroup = flatGroupMap[groupName][subIndex];
    return checkAccuracy(subGroup, curr);
  });
});

const outputPath = path.join(__dirname, "result_stream_v2.jsonl");
fs.writeFileSync(outputPath, ""); // 清空旧文件

// ⚙️ 执行流式策略（每期写入一行）
enhancedSelectGroups({
  groupAccuracyMap,
  flatGroupMap,
  numberGroupMap,
  historyData,
  windowSize: 200,
  cooldownThreshold: 3,
  cooldownPeriod: 10,
  diversityLimit: 4,
  recentHotWindow: 3,
  maxRecentRepeat: 2,
  onEachPeriod: (result) => {
    fs.appendFileSync(outputPath, JSON.stringify(result) + "\n");
  },
});

console.log("✅ 已输出每期预测结果至 result_stream_v2.jsonl");


